package net.lesscoding.consumer;

import net.lesscoding.common.Const;
import org.apache.rocketmq.client.consumer.DefaultLitePullConsumer;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @author eleven
 * @date 2023/10/10 22:35
 * @apiNote 消费者
 */
public class SomeSonConsumer {
    public static void main(String[] args) throws MQClientException {
        // 定义一个pull消费者
        DefaultLitePullConsumer consumer = new DefaultLitePullConsumer("cg");
        // 定义一个push消费者
        DefaultMQPushConsumer pushConsumer = new DefaultMQPushConsumer("cg");
        // 指定nameserver
        pushConsumer.setNamesrvAddr(Const.TS_NAME_SRV_ADDR_OS1);
        // 指定从第一条消息开始消费
        pushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 指定topic和tag
        pushConsumer.subscribe("someTopic","*");

        // 采用广播模式消费，默认为集群
        pushConsumer.setMessageModel(MessageModel.BROADCASTING);
        /**
         * 顺序消息消费失败的消费重试时间间隔，默认为1000ms，取值范围为[10, 30000)ms
         */
        pushConsumer.setSuspendCurrentQueueTimeMillis(100);
        // 修改消费重试次数
        pushConsumer.setMaxReconsumeTimes(10);
        // 注册消息监听器
        pushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            /**
             * 一单broker中有了其订阅的消息就会触发该方法的执行
             * 其返回值为当前consumer消费的状态
             * @param msgList                       消息列表
             * @param consumeConcurrentlyContext
             * @return
             */
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : msgList) {
                    System.out.println(msg);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        pushConsumer.start();
        System.out.println("Consumer Started");
    }
}
